#include "err_and_log.h"
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>


/*------------------------------------------------------------------------
 * errexit - print an error message and exit
 *------------------------------------------------------------------------
 */

int		ftp_log_write(const char *logstr);

void	errexit(const char *format, ...)
{
	char	errstr[LOG_STR_SIZE];
    va_list  args;
    va_start(args, format);
    _vsnprintf(errstr,LOG_STR_SIZE, format, args);
	fprintf(stderr, errstr);
	putchar('\n');
	ftp_log_write(errstr);
    va_end(args);
    WSACleanup();
    exit(1);
}

void	errmsg(const char *format, ...)
{
	char	errstr[LOG_STR_SIZE];
    va_list  args;
    va_start(args, format);
    _vsnprintf(errstr,LOG_STR_SIZE, format, args);
	fprintf(stderr, errstr);
	putchar('\n');
	ftp_log_write(errstr);
    va_end(args);
    return ;

}

int		ftp_log(const char *format, ...)
{
	char	logstr[LOG_STR_SIZE];
    va_list  args;
    va_start(args, format);
    _vsnprintf(logstr,LOG_STR_SIZE, format, args);
	va_end(args);
	if(ftp_log_write(logstr) != 0)
		return -1;
	else
		return 0;
}

CRITICAL_SECTION critlock;

int		ftp_log_write(const char *logstr)
{
	FILE	*logfptr;
	time_t	ltime;
	int		ret;
	char	now[30];
	
	time( &ltime);
	strcpy(now, ctime( &ltime));
	*(strchr(now, '\n')) = '\0';

	EnterCriticalSection( &critlock );
	if( (logfptr = fopen(LOG_FILE, "a")) != NULL)
	{
		fprintf(logfptr,"[%s]:\t%s\r\n" , now, logstr);
		ret = 0;
		fclose(logfptr);
	}
	else
		ret = -1;
	LeaveCriticalSection( &critlock);
	
	return ret;
}